<template>
  <!-- 表单 -->
  <el-form label-width="120px" ref="FormRef" :model="skuInfo" :rules="rules">
    <!-- spu名称 -->
    <el-form-item label="SPU名称">{{ spu.spuName }} </el-form-item>
    <!-- sku名称 -->
    <el-form-item label="sku名称" prop="skuName">
      <el-input placeholder="sku名称" v-model="skuInfo.skuName"> </el-input>
    </el-form-item>
    <!-- 价格 -->
    <el-form-item label="价格(元)" prop="price">
      <el-input placeholder="价格" v-model="skuInfo.price"> </el-input>
    </el-form-item>
    <!-- 重量 -->
    <el-form-item label="重量(千克)" prop="weight">
      <el-input placeholder="重量" v-model="skuInfo.weight"> </el-input>
    </el-form-item>
    <!-- 规格描述 -->
    <el-form-item label="规格描述" prop="skuDesc">
      <el-input type="textarea" placeholder="规格描述" v-model="skuInfo.skuDesc" rows="4"> </el-input>
    </el-form-item>
    <!-- 平台属性 -->
    <el-form-item label="平台属性" prop="skuAttrValueList">
      <!-- 小表单 -->
      <el-form inline>
        <el-form-item :label="attr.attrName" style="margin-left: 50px" v-for="(attr, index) in attrList" :key="attr.id">
          <el-select placeholder="请选择" v-model="skuInfo.skuSaleAttrValueList[index]">
            <el-option :label="val.valueName" v-for="val in attr.attrValueList" :key="val.id" :value="val.id + '_' + attr.id">{{ val.valueName }}</el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </el-form-item>
    <!-- 销售属性 -->
    <el-form-item label="销售属性" prop="skuSaleAttrValueList">
      <!-- 小表单 -->
      <el-form inline>
        <el-form-item :label="attr.saleAttrName" style="margin-left: 50px" v-for="(attr, index) in spuSaleAttrList" :key="attr.id">
          <el-select placeholder="请选择" v-model="skuInfo.skuSaleAttrValueList[index]">
            <el-option v-for="val in attr.spuSaleAttrValueList" :key="val.id" :value="(val.id as number)" :label="val.saleAttrValueName"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </el-form-item>
    <!-- 图片的列表 -->
    <el-form-item label="图片列表" prop="skuImageList">
      <el-table row-key="id" :data="spuImageList" stripe border style="width: 100%" ref="tableRef" @selection-change="handlerSelectionChange">
        <!-- 全选 -->
        <el-table-column type="selection" width="55" />
        <!-- 图片 -->
        <el-table-column label="图片">
          <template v-slot="{ row, $index }">
            <el-image :src="row.imgUrl" style="width: 100px; height: 100px"></el-image>
          </template>
        </el-table-column>
        <!-- 名称 -->
        <el-table-column property="imgName" label="名称" />
        <!-- 操作-->
        <el-table-column label="操作">
          <template #default="{ row, $index }">
            <el-tag type="success" v-if="row.isDefault === '1'">默认</el-tag>
            <el-button size="default" type="primary" v-else @click="setDefault(row)">设置默认</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <!-- 底部的两个按钮 -->
    <el-form-item>
      <el-button size="default" type="primary" @click="saveSkuInfo">保存</el-button>
      <el-button size="default" @click="emits('setShowStatus', ShowStatus.SPU_LIST)">取消</el-button>
    </el-form-item>
  </el-form>
</template>
<script lang="ts">
export default {
  name: "SkuForm",
};
</script>
<script lang="ts" setup>
// 引入标识数据
import type { AttrListModel } from "@/api/product/model/attrModel";
import type { SkuModel } from "@/api/product/model/skuModel";
import { reactive } from "vue";
import { ShowStatus } from "./types";
import { ref, onMounted, nextTick } from "vue";
import type { SpuImageListModel, SpuImageModel, SpuSaleAttrListModel } from "@/api/product/model/spuModel";
import { reqGetAttrList } from "@/api/product/attr";
import useCategoryStore from "@/stores/category";
import { reqGetSpuInfoImageList, reqGetSpuInfoSaleAttrList } from "@/api/product/spu";
import { ElMessage, type ElTable } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import { reqAddSkuInfo } from "@/api/product/sku";
// 用于接受父级组件的自定义事件
const emits = defineEmits(["setShowStatus"]);
// 定义一个接口，用来限制传入进来的数据
interface Props {
  spu: {
    id: number;
    spuName: string;
  };
}

// 定义变量 用来收集所有的平台属性数组数据
const attrList = ref<AttrListModel>([]);
// 定义变量  用来收集当前的这个spu对象下所拥有的销售属性数组数据
const spuSaleAttrList = ref<SpuSaleAttrListModel>([]);
// 定义变量 用来收集当前的这个spu对象下所拥有的图片；列表数组数据
const spuImageList = ref<SpuImageListModel>([]);
// 获取table对象的数据
const tableRef = ref<InstanceType<typeof ElTable>>();

// 页面加载完成之后获取平台属性，spu销售属性，spu图片
onMounted(async () => {
  attrList.value = await reqGetAttrList({
    category1Id: useCategoryStore().getCategory1Id as number,
    category2Id: useCategoryStore().getCategory2Id as number,
    category3Id: useCategoryStore().getCategory3Id as number,
  });
});

onMounted(async () => {
  spuSaleAttrList.value = await reqGetSpuInfoSaleAttrList(props.spu.id);
});

onMounted(async () => {
  spuImageList.value = await reqGetSpuInfoImageList(props.spu.id);
  // 让每一个图片中都有isDefault这个属性  所有的值是 0   只有第一个是1
  spuImageList.value.forEach((item) => {
    item.isDefault = "0";
  });
  //设置第一个为1  因为是默认的
  spuImageList.value[0].isDefault = "1";
  nextTick(() => {
    tableRef.value?.toggleRowSelection(spuImageList.value[0], true);
  });
  // 把这个默认的图片的地址存储起来
  skuInfo.skuDefaultImg = spuImageList.value[0].imgUrl;
});

// 接受父级组件传递过来的数据
const props = defineProps<Props>();
// 准备skuInfo对象的数据
const skuInfo = reactive<SkuModel>({
  isSale: 1, // 上下架的标识 默认上架
  tmId: undefined, //品牌的id
  skuDesc: "", //描述信息
  price: 0, //价格
  weight: 0, //重量
  skuName: "", //名字
  skuDefaultImg: "", // 默认的图片的地址
  skuAttrValueList: [], //平台属性对象数组
  skuImageList: [], //图片列表数组
  skuSaleAttrValueList: [], //销售属性值对象列表数组
});

//设置某一个的图片是默认的
const setDefault = (row: SpuImageModel) => {
  // 排他思想
  spuImageList.value.forEach((item) => {
    item.isDefault = "0";
  });
  row.isDefault = "1";
  tableRef.value?.toggleRowSelection(row, true);
  skuInfo.skuDefaultImg = row.imgUrl;
};

// 表格中的图片选中操作的方法
const handlerSelectionChange = (rows?: SpuImageListModel) => {
  // 立刻更新图片数组的数据
  skuInfo.skuImageList = rows as any;
};
// 定义form的dom元素
const FormRef = ref<FormInstance>();

// 定义rules规则
const rules = reactive<FormRules>({
  skuName: [{ required: true, message: "您必须填写此项目", trigger: "blur" }],
  price: [{ required: true, message: "您必须填写此项目", trigger: "blur" }],
  weight: [{ required: true, message: "您必须填写此项目", trigger: "blur" }],
  skuDesc: [{ required: true, message: "您必须填写此项目", trigger: "blur" }],
  skuAttrValueList: [{ required: true, message: "您必须填写此项目", trigger: "change", type: "array" }],
  skuSaleAttrValueList: [{ required: true, message: "您必须填写此项目", trigger: "change", type: "array" }],
  skuImageList: [{ required: true, message: "您必须填写此项目", trigger: "change", type: "array" }],
});
// 点击保存按钮的回调
const saveSkuInfo = async () => {
  //先表单验证
  await FormRef.value?.validate();

  // 调用接口,过滤数据
  await reqAddSkuInfo({
    // 直接过滤数据
    ...skuInfo,
    spuId: props.spu.id, // spu的id
    category3Id: useCategoryStore().getCategory3Id as number, // 三级分类的id
    skuAttrValueList: skuInfo.skuAttrValueList // 过滤平台属性数据
      .map((valueIdAttrId) => {
        // 取出值的id和对象的id
        const [valueId, attrId] = (valueIdAttrId as any).split("_");
        return {
          valueId: +valueId,
          attrId: +attrId,
        };
      }),
    // 过滤销售属性数据数组
    skuSaleAttrValueList: skuInfo.skuSaleAttrValueList.filter(Boolean).map((valueId) => {
      return {
        saleAttrValueId: +valueId,
      };
    }),
    // 过滤图片数组数据
    skuImageList: skuInfo.skuImageList.map((item) => ({
      imgName: item.imgName as string,
      imgUrl: item.imgUrl as string,
      spuImgId: item.id as number,
      isDefault: item.isDefault as string,
    })),
  });
  ElMessage.success("添加SKU成功");
  emits("setShowStatus", ShowStatus.SPU_LIST);
};
</script>
<style scoped></style>
